home *** CD-ROM | disk | FTP | other *** search
/ Info-Mac 3 / Info_Mac_1994-01.iso / Development / Information / Mac Programming Secrets 1.0.1 / Chapter 10 / Standard Stuff.c < prev    next >
C/C++ Source or Header  |  1992-05-19  |  20KB  |  684 lines

  1. #include "Standard Stuff.h"
  2. #include "Command Period.h"
  3. #include "EnterPassword.h"
  4. #include "Hide Menubar.h"
  5. #include "Traps.h"
  6. #include "SpinningCursor.h"
  7.  
  8. /*******************************************************************************
  9.  
  10.     The “g” prefix is used to emphasize that a variable is global.
  11.  
  12. *******************************************************************************/
  13.  
  14. SysEnvRec    gMac;                /*    gMac is used to hold the result of a
  15.                                     SysEnvirons call. This makes it convenient
  16.                                     for any routine to check the environment. */
  17.  
  18. Boolean        gQuit;                /*    We set this to TRUE when the user selects
  19.                                     Quit from the File menu. Our main event
  20.                                     loop exists when gQuit is TRUE. */
  21.  
  22. Boolean        gInBackground;        /*    gInBackground is maintained by our osEvent
  23.                                     handling routines. Any part of the program
  24.                                     can check it to find out if it is currently
  25.                                     in the background. */
  26.  
  27.  
  28. /*******************************************************************************
  29.  
  30.     Define HiWrd and LoWrd macros for efficiency.
  31.  
  32. *******************************************************************************/
  33.  
  34. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  35. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  36.  
  37.  
  38. /*******************************************************************************
  39.  
  40.     main
  41.  
  42.     Entry point for our program. We initialize the toolbox, make sure we are
  43.     running on a sufficiently studly machine, and put up the menubar. Finally,
  44.     we start polling for events and handling them by entering our main event
  45.     loop.
  46.  
  47. *******************************************************************************/
  48. main()
  49. {
  50.     /*    If you have stack requirements that differ from the default,
  51.         then you could use SetApplLimit to increase StackSpace at
  52.         this point, before calling MaxApplZone. */
  53.  
  54.     MaxApplZone();                    /* Expand the heap so code segments load
  55.                                        at the top */
  56.     InitToolbox();                    /* Initialize the program */
  57.     MainEventLoop();                /* Call the main event loop */
  58. }
  59.  
  60.  
  61. /*******************************************************************************
  62.  
  63.     InitToolbox
  64.  
  65.     Set up the whole world, including global variables, Toolbox managers, and
  66.     menus.
  67.  
  68. *******************************************************************************/
  69. void InitToolbox()
  70. {
  71.     Handle        menuBar;
  72.     EventRecord event;
  73.     short        count;
  74.  
  75.     gInBackground = FALSE;
  76.     gQuit = FALSE;
  77.  
  78.     InitGraf((Ptr) &qd.thePort);
  79.     InitFonts();
  80.     InitWindows();
  81.     InitMenus();
  82.     TEInit();
  83.     InitDialogs(NIL);
  84.     InitCursor();
  85.  
  86.     /*    This next bit of code waits until MultiFinder brings our application
  87.         to the front. This gives us a better effect if we open a window at
  88.         startup. */
  89.  
  90.     for (count = 1; count <= 3; ++count)
  91.         EventAvail(everyEvent, &event);
  92.  
  93.     SysEnvirons(curSysEnvVers, &gMac);
  94.  
  95.     if (gMac.machineType < 0)
  96.         DeathAlert(errWimpyROMs);
  97.  
  98.     if (gMac.systemVersion < 0x0600)
  99.         DeathAlert(errWimpySystem);
  100.  
  101.     if (!TrapExists(_WaitNextEvent))
  102.         DeathAlert(errWeirdSystem);
  103.  
  104.     menuBar = GetNewMBar(rMenuBar);            /* Read menus into menu bar */
  105.     if ( menuBar == NIL )
  106.          DeathAlert(errNoMenuBar);
  107.     SetMenuBar(menuBar);                    /* Install menus */
  108.     DisposHandle(menuBar);
  109.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* Add DA names to Apple menu */
  110.     AdjustMenus();
  111.     DrawMenuBar();
  112.  
  113.     InitCursorCtl(NIL);                                                /* +++ */
  114. }
  115.  
  116.  
  117. /*******************************************************************************
  118.  
  119.     MainEventLoop
  120.  
  121.     Get events forever, and handle them by calling HandleEvent. First, call
  122.     DoAdjustCursor to set our cursor shape, and to set the cursor region. We
  123.     then call WaitNextEvent() to get the event. This is OK, because we know
  124.     we’re running on System 6.0 or later by this time. If we got an event, we
  125.     handle it by calling HandleEvent(). But before doing that, we call
  126.     DoAdjustCursor again in case our application had fallen asleep under
  127.     MultiFinder.
  128.  
  129. *******************************************************************************/
  130. void MainEventLoop()
  131. {
  132.     RgnHandle    cursorRgn;
  133.     Boolean        gotEvent;
  134.     EventRecord    event;
  135.     Point        mouse;
  136.  
  137.     cursorRgn = NIL;
  138.     while ( !gQuit ) {
  139.         gotEvent = WaitNextEvent(everyEvent, &event, MAXLONG, cursorRgn);
  140.         if ( gotEvent ) {
  141.             StartAsyncSpinning(10);                                    /* +++ */
  142.             HandleEvent(&event);
  143.             StopAsyncSpinning();                                    /* +++ */
  144.         }
  145.     }
  146.     ShowMenuBar();                                                    /* +++ */
  147. }
  148.  
  149.  
  150. /*******************************************************************************
  151.  
  152.     HandleEvent
  153.  
  154.     Do the right thing for an event. Determine what kind of event it is, and
  155.     call the appropriate routines.
  156.  
  157. *******************************************************************************/
  158. void HandleEvent(EventRecord *event)
  159. {
  160.     switch ( event->what ) {
  161.         case mouseDown:
  162.             HandleMouseDown(event);
  163.             break;
  164.         case keyDown:
  165.         case autoKey:
  166.             HandleKeyPress(event);
  167.             break;
  168.         case activateEvt:
  169.             HandleActivate(event);
  170.             break;
  171.         case updateEvt:
  172.             HandleUpdate(event);
  173.             break;
  174.         case diskEvt:
  175.             HandleDiskInsert(event);
  176.             break;
  177.         case osEvt:
  178.             HandleOSEvent(event);
  179.             break;
  180.     }
  181. }
  182.  
  183.  
  184. /*******************************************************************************
  185.  
  186.     HandleActivate
  187.  
  188.     This is called when a window is activated or deactivated. In this sample,
  189.     the Window Manager’s handling of activate and deactivate events is
  190.     sufficient. Other applications may have TextEdit records, controls, lists,
  191.     etc., to activate/deactivate.
  192.  
  193. *******************************************************************************/
  194. void HandleActivate(EventRecord *event)
  195. {
  196.     WindowPtr    theWindow;
  197.     Boolean        becomingActive;
  198.  
  199.     theWindow = (WindowPtr) event->message;
  200.     becomingActive = (event->modifiers & activeFlag) != 0;
  201.     if ( IsAppWindow(theWindow) ) {
  202.         DrawGrowIcon(theWindow);
  203.         /* DoActivateWindow(theWindow, becomingActive) */;
  204.     }
  205. }
  206.  
  207.  
  208. /*******************************************************************************
  209.  
  210.     HandleDiskInsert
  211.  
  212.     Called when we get a disk inserted event. Check the upper word of the
  213.     event message; if it’s non-zero, then a bad disk was inserted, and it
  214.     needs to be formatted.
  215.  
  216. *******************************************************************************/
  217. void HandleDiskInsert(EventRecord *event)
  218. {
  219.     Point    aPoint = {100, 100};
  220.  
  221.     if ( HiWrd(event->message) != noErr ) {
  222.         (void) DIBadMount(aPoint, event->message);
  223.     }
  224. }
  225.  
  226.  
  227. /*******************************************************************************
  228.  
  229.     HandleKeyPress
  230.  
  231.     The user pressed a key. What are you going to do about it?
  232.  
  233. *******************************************************************************/
  234. void HandleKeyPress(EventRecord *event)
  235. {
  236.     char    key;
  237.  
  238.     key = event->message & charCodeMask;
  239.     if ( event->modifiers & cmdKey ) {        /* Command key down? */
  240.         if (key == ' ') {                                            /* +++ */
  241.             ToggleMenuBar();                                        /* +++ */
  242.         } else {                                                    /* +++ */
  243.             AdjustMenus();                    /* Enable/disable/check menu items properly */
  244.             HandleMenuCommand(MenuKey(key));
  245.         }
  246.     } else {
  247.         /* DoKeyPress(event) */;
  248.     }
  249. }
  250.  
  251.  
  252. /*******************************************************************************
  253.  
  254.     HandleMouseDown
  255.  
  256.     Called to handle mouse clicks. The user could have clicked anywhere, so
  257.     let’s first find out where by calling FindWindow. That returns a number
  258.     indicating where in the screen the mouse was clicked. “switch” on that
  259.     number and call the appropriate routine.
  260.  
  261. *******************************************************************************/
  262. void HandleMouseDown(EventRecord *event)
  263. {
  264.     long        newSize;
  265.     Rect        growRect;
  266.     WindowPtr    theWindow;
  267.     short        part = FindWindow(event->where, &theWindow);
  268.  
  269.     switch ( part ) {
  270.         case inMenuBar:                /* Process a mouse menu command (if any) */
  271.             AdjustMenus();
  272.             HandleMenuCommand(MenuSelect(event->where));
  273.             break;
  274.         case inSysWindow:            /* Let the system handle the mouseDown */
  275.             SystemClick(event, theWindow);
  276.             break;
  277.         case inContent:
  278.             if ( theWindow != FrontWindow() )
  279.                 SelectWindow(theWindow);
  280.             else
  281.                 /* DoContentClick(event, theWindow) */;
  282.             break;
  283.         case inDrag:                /* Pass screenBits.bounds to get all gDevices */
  284.             DragWindow(theWindow, event->where, &qd.screenBits.bounds);
  285.             break;
  286.         case inGrow:
  287.             growRect = qd.screenBits.bounds;
  288.             growRect.top = growRect.left = 80;        /* Arbitrary minimum size. */
  289.             newSize = GrowWindow(theWindow, event->where, &growRect);
  290.             if (newSize != 0) {
  291.                 InvalidateScrollbars(theWindow);
  292.                 SizeWindow(theWindow, LoWrd(newSize), HiWrd(newSize), TRUE);
  293.                 InvalidateScrollbars(theWindow);
  294.             }
  295.             break;
  296.         case inGoAway:
  297.             if (TrackGoAway(theWindow, event->where))  {
  298.                 CloseAnyWindow(theWindow);
  299.             }
  300.             break;
  301.         case inZoomIn:
  302.         case inZoomOut:
  303.             if (TrackBox(theWindow, event->where, part)) {
  304.                 SetPort(theWindow);
  305.                 EraseRect(&theWindow->portRect);
  306.                 ZoomWindow(theWindow, part, TRUE);
  307.                 InvalRect(&theWindow->portRect);
  308.             }
  309.             break;
  310.     }
  311. }
  312.  
  313.  
  314. /*******************************************************************************
  315.  
  316.     HandleOSEvent
  317.  
  318.     Deal with OSEvents (formerly, app4Events). These are message that
  319.     MultiFinder -- known as the Process Manager under System 7.0 -- sends to
  320.     us. Here, we deal with suspend and resume message.
  321.  
  322. *******************************************************************************/
  323. void HandleOSEvent(EventRecord *event)
  324. {
  325.     switch ((event->message >> 24) & 0x00FF) {        /* High byte of message */
  326.         case suspendResumeMessage:
  327.  
  328.             /*    In our SIZE resource, we say that we are MultiFinder aware.
  329.                 This means that we take on the responsibility of activating
  330.                 and deactivating our own windows on suspend/resume events. */
  331.  
  332.             gInBackground = (event->message & resumeFlag) == 0;
  333.             if (FrontWindow()) {
  334.                 DrawGrowIcon(FrontWindow());
  335.                 /* DoActivateWindow(FrontWindow(), !gInBackground); */
  336.             }
  337.             break;
  338.         case mouseMovedMessage:
  339.             break;
  340.     }
  341. }
  342.  
  343.  
  344. /*******************************************************************************
  345.  
  346.     HandleUpdate
  347.  
  348.     This is called when an update event is received for a window. It calls
  349.     DoUpdateWindow to draw the contents of an application window. As an
  350.     efficiency measure that does not have to be followed, it calls the drawing
  351.     routine only if the visRgn is non-empty. This will handle situations where
  352.     calculations for drawing or drawing itself is very time-consuming.
  353.  
  354. *******************************************************************************/
  355. void HandleUpdate(EventRecord *event)
  356. {
  357.     WindowPtr    theWindow = (WindowPtr) event->message;
  358.     if ( IsAppWindow(theWindow) ) {
  359.         BeginUpdate(theWindow);                /* This sets up the visRgn */
  360.         if (!EmptyRgn(theWindow->visRgn)) {    /* Draw if updating needs to be done */
  361.             SetPort(theWindow);
  362.             EraseRgn(theWindow->visRgn);
  363.             /* DoUpdateWindow(event) */;
  364.             DrawGrowIcon(theWindow);
  365.         }
  366.         EndUpdate(theWindow);
  367.     }
  368. }
  369.  
  370.  
  371. /*******************************************************************************
  372.  
  373.     AdjustMenus
  374.  
  375.     Enable and disable menus based on the current state. The user can only
  376.     select enabled menu items. We set up all the menu items before calling
  377.     MenuSelect or MenuKey, since these are the only times that a menu item can
  378.     be selected. Note that MenuSelect is also the only time the user will see
  379.     menu items. This approach to deciding what enable/disable state a menu
  380.     item has the advantage of concentrating all the decision-making in one
  381.     routine, as opposed to being spread throughout the application. Other
  382.     application designs may take a different approach that is just as valid.
  383.  
  384. *******************************************************************************/
  385. void AdjustMenus()
  386. {
  387.     WindowPtr    window;
  388.     MenuHandle    menu;
  389.  
  390.     window = FrontWindow();
  391.  
  392.     menu = GetMHandle(mFile);
  393.     if ( window != NIL )
  394.         EnableItem(menu, iClose);
  395.     else
  396.         DisableItem(menu, iClose);
  397.  
  398.     menu = GetMHandle(mEdit);
  399.     if ( IsDAWindow(window) ) {        /* A desk accessory might need the edit menu… */
  400.         EnableItem(menu, iUndo);
  401.         EnableItem(menu, iCut);
  402.         EnableItem(menu, iCopy);
  403.         EnableItem(menu, iClear);
  404.         EnableItem(menu, iPaste);
  405.     } else {                        /* … but we don’t use it. */
  406.         DisableItem(menu, iUndo);
  407.         DisableItem(menu, iCut);
  408.         DisableItem(menu, iCopy);
  409.         DisableItem(menu, iClear);
  410.         DisableItem(menu, iPaste);
  411.     }
  412. }
  413.  
  414.  
  415. /*******************************************************************************
  416.  
  417.     HandleMenuCommand
  418.  
  419.     This is called when an item is chosen from the menu bar (after calling
  420.     MenuSelect or MenuKey). It performs the right operation for each command.
  421.     It is good to have both the result of MenuSelect and MenuKey go to one
  422.     routine like this to keep everything organized.
  423.  
  424. *******************************************************************************/
  425. void HandleMenuCommand(menuResult)
  426.     long        menuResult;
  427. {
  428.     short        menuID;                /* The resource ID of the selected menu */
  429.     short        menuItem;            /* The item number of the selected menu */
  430.     Str255        daName;
  431.  
  432.     menuID = HiWrd(menuResult);
  433.     menuItem = LoWrd(menuResult);
  434.     switch ( menuID ) {
  435.         case mApple:
  436.             switch ( menuItem ) {
  437.                 case iAbout:
  438.                     (void) Alert(rAboutAlert, NIL);
  439.                     break;
  440.                 default:            /* All non-About items in this menu are DAs */
  441.                     GetItem(GetMHandle(mApple), menuItem, daName);
  442.                     (void) OpenDeskAcc(daName);
  443.                     break;
  444.             }
  445.             break;
  446.         case mFile:
  447.             switch ( menuItem ) {
  448.                 case iNew:
  449.                     /* DoNewWindow(); */
  450.                     break;
  451.                 case iClose:
  452.                     CloseAnyWindow(FrontWindow());
  453.                     break;
  454.                 case iQuit:
  455.                     gQuit = TRUE;
  456.                     break;
  457.             }
  458.             break;
  459.         case mEdit:
  460.             switch (menuItem) {
  461.                 /* Call SystemEdit for DA editing & MultiFinder */
  462.                 /* since we don’t do any Editing */
  463.                 case iUndo:
  464.                 case iCut:
  465.                 case iCopy:
  466.                 case iPaste:
  467.                 case iClear:
  468.                     (void) SystemEdit(menuItem-1);
  469.                     break;
  470.             }
  471.             break;
  472.         case mStuff:                                                /* +++ */
  473.             switch (menuItem) {                                        /* +++ */
  474.                 case iTestCmdPeriod:                                /* +++ */
  475.                     TestCommandPeriod();                            /* +++ */
  476.                     break;                                            /* +++ */
  477.                 case iEnterPassword:                                /* +++ */
  478.                     EnterPassword();                                /* +++ */
  479.                     break;                                            /* +++ */
  480.             }                                                        /* +++ */
  481.             break;                                                    /* +++ */
  482.     }
  483.     HiliteMenu(0);        /* Unhighlight what MenuSelect or MenuKey hilited */
  484. }
  485.  
  486.  
  487. /*******************************************************************************
  488.  
  489.     CloseAnyWindow
  490.  
  491.     Close the given window in a manner appropriate for that window. If the
  492.     window belongs to a DA, we call CloseDeskAcc. For dialogs, we simply hide
  493.     the window. If we had any document windows, we would probably call either
  494.     DisposeWindow or CloseWindow after disposing of any document data and/or
  495.     controls.
  496.  
  497. *******************************************************************************/
  498. void CloseAnyWindow(WindowPtr window)
  499. {
  500.     if (IsDAWindow(window)) {
  501.         CloseDeskAcc( ( (WindowPeek) window )->windowKind );
  502.     } else if (IsDialogWindow(window)) {
  503.         HideWindow(window);
  504.     } else if (IsAppWindow(window)) {
  505.         DisposeWindow(window);
  506.     }
  507. }
  508.  
  509.  
  510. /*******************************************************************************
  511.  
  512.     DeathAlert
  513.  
  514.     Display an alert that tells the user an error occurred, then exit the
  515.     program. This routine is used as an ultimate bail-out for serious errors
  516.     that prohibit the continuation of the application. The error number is
  517.     used to index an 'STR#' resource so that a relevant message can be
  518.     displayed.
  519.  
  520. *******************************************************************************/
  521. void DeathAlert(short errNumber)
  522. {
  523.     short        itemHit;
  524.     Str255        theMessage;
  525.  
  526.     SetCursor(&qd.arrow);
  527.     GetIndString(theMessage, rErrorStrings, errNumber);
  528.     ParamText(theMessage, NIL, NIL, NIL);
  529.     itemHit = StopAlert(rErrorAlert, NIL);
  530.     ExitToShell();
  531. }
  532.  
  533.  
  534. /*******************************************************************************
  535.  
  536.     IsAppWindow
  537.  
  538.     Check to see if a window belongs to the application. If the window pointer
  539.     passed was NIL, then it could not be an application window. WindowKinds
  540.     that are negative belong to the system and windowKinds less than userKind
  541.     are reserved by Apple except for windowKinds equal to dialogKind, which
  542.     mean it is a dialog.
  543.  
  544. *******************************************************************************/
  545. Boolean IsAppWindow(WindowPtr window)
  546. {
  547.     short        windowKind;
  548.  
  549.     if ( window == NIL )
  550.         return false;
  551.     else {
  552.         windowKind = ((WindowPeek) window)->windowKind;
  553.         return ((windowKind >= userKind) || (windowKind == dialogKind));
  554.     }
  555. }
  556.  
  557.  
  558. /*******************************************************************************
  559.  
  560.     IsDAWindow
  561.  
  562.     Check to see if a window belongs to a desk accessory. It belongs to a DA
  563.     if the windowKind field of the window record is negative.
  564.  
  565. *******************************************************************************/
  566. Boolean IsDAWindow(WindowPtr window)
  567. {
  568.     if ( window == NIL )
  569.         return false;
  570.     else
  571.         return ( ((WindowPeek) window)->windowKind < 0 );
  572. }
  573.  
  574.  
  575. /*******************************************************************************
  576.  
  577.     IsDialogWindow
  578.  
  579.     Check to see if a window is a dialog window. We can determine this be
  580.     checking to see if the windowKind field is equal to dialogKind.
  581.  
  582. *******************************************************************************/
  583. Boolean IsDialogWindow(WindowPtr window)
  584. {
  585.     if ( window == NIL )
  586.         return false;
  587.     else
  588.         return ( ((WindowPeek) window)->windowKind == dialogKind );
  589. }
  590.  
  591.  
  592. /*******************************************************************************
  593.  
  594.     InvalidateScrollbars
  595.  
  596.     Call InvalRect on the right and bottom edges of a window. This routine is
  597.     called during the resizing of a window to take care of the scrollbar lines
  598.     and grow icon.
  599.  
  600. *******************************************************************************/
  601. void InvalidateScrollbars(WindowPtr theWindow)
  602. {
  603.     Rect    tempRect;
  604.  
  605.     SetPort(theWindow);
  606.  
  607.     tempRect = theWindow->portRect;
  608.     tempRect.left = tempRect.right - 15;
  609.     InvalRect(&tempRect);
  610.     EraseRect(&tempRect);
  611.  
  612.     tempRect = theWindow->portRect;
  613.     tempRect.top = tempRect.bottom - 15;
  614.     InvalRect(&tempRect);
  615.     EraseRect(&tempRect);
  616. }
  617.  
  618.  
  619. /*******************************************************************************
  620.  
  621.     TrapExists
  622.  
  623.     Check to see if a given trap is implemented. The recommended approach to
  624.     see if a trap is implemented is to see if the address of the trap routine
  625.     is the same as the address of the _Unimplemented trap. However, we must
  626.     also make sure that the trap is contained in the trap table on the machine
  627.     we’re running on. Not all Macintoshes have the same sized trap tables. We
  628.     call NumToolboxTraps to find out the size of the table. If the trap we are
  629.     examining falls off the end, then we treat it as automatically being
  630.     unimplemented.
  631.  
  632. *******************************************************************************/
  633. Boolean    TrapExists(short theTrap)
  634. {
  635.     TrapType    theTrapType;
  636.  
  637.     theTrapType = GetTrapType(theTrap);
  638.     if ((theTrapType == ToolTrap) && ((theTrap &= 0x07FF) >= NumToolboxTraps()))
  639.         return false;
  640.     else
  641.         return (NGetTrapAddress(_Unimplemented, ToolTrap) !=
  642.                 NGetTrapAddress(theTrap, theTrapType));
  643. }
  644.  
  645.  
  646. /*******************************************************************************
  647.  
  648.     GetTrapType
  649.  
  650.     Check the bits of a trap number to determine its type. If bit 11 is set,
  651.     it’s a toolbox trap. Otherwise, it’s an OS trap.
  652.  
  653. *******************************************************************************/
  654. TrapType    GetTrapType(short theTrap)
  655. {
  656.     if ((theTrap & 0x0800) == 0)                    /* Per D.A. */
  657.         return (OSTrap);
  658.     else
  659.         return (ToolTrap);
  660. }
  661.  
  662.  
  663. /*******************************************************************************
  664.  
  665.     NumToolboxTraps
  666.  
  667.     Find the size of the Toolbox trap table. This can be either 0x0200 or
  668.     0x0400 bytes, depending on which Macintosh we are running on. We determine
  669.     the size by taking advantage of an anomaly of the smaller trap table: any
  670.     entries that fall beyond the end of the table are mirrored back down into
  671.     the lower part. For example, on a large table, trap numbers A86E and AA6E
  672.     correspond to different routines. However, on a small table, they
  673.     correspond to the same routine. By checking the addresses of these
  674.     routines, we can determine the size of the table.
  675.  
  676. *******************************************************************************/
  677. short    NumToolboxTraps(void)
  678. {
  679.     if (NGetTrapAddress(0xA86E, ToolTrap) == NGetTrapAddress(0xAA6E, ToolTrap))
  680.         return (0x200);
  681.     else
  682.         return (0x400);
  683. }
  684.